<template>
  <div class="sidebar">
    <Menu ref="side_menu" width="200" theme="dark" :active-name="activeName" :open-names="openName">
      <Submenu v-for="menu in menuList" :key="menu.item" :name="menu.id">
        <template slot="title">
          <Icon :type="menu.icon" />{{ menu.text }}
        </template>
        <template v-if="menu.children.length">
          <block v-for="children in menu.children" :key="children.id">
            <MenuGroup v-if="children.type && children.type === 'group' && children.children.length" :title="children.text">
              <MenuItem v-for="child in children.children" :key="child.id" :name="child.id" :to="'/' + child.link"><span class="circle" />{{ child.text }}</MenuItem>
            </MenuGroup>
            <MenuItem v-else :name="children.id" :to="'/' + children.link">{{ children.text }}</MenuItem>
          </block>
        </template>
      </Submenu>
    </Menu>
  </div>
</template>

<script>
export default {
  data () {
    return {
      menuList: [],
      activeName: '',
      openName: []
    }
  },
  watch: {
    $route ($route) {
      this.openMenu($route.meta.id)
    }
  },
  created () {
    this.$store.dispatch('isShowMeta').then(data => {
      let routers = this.$router.options.routes
      const filterRouter = (item, e) => {
        e.forEach(todo => {
          if (item.viewUrl == todo.path && !item.hasRight) { // 没权限
            todo.hidden = true
          } else if (item.viewUrl == todo.path && item.hasRight) { // 有权限
            todo.hidden = false
          }
          if (todo.children && todo.children.length) {
            filterRouter(item, todo.children)
          }
        })
      }
      data.forEach(item => {
        filterRouter(item, routers)
      })
      this.initMenu()
      this.$nextTick(() => {
        this.openMenu(this.$route.meta.id)
      })
    })
      // this.initMenu()
      // this.$nextTick(() => {
      //   this.openMenu(this.$route.meta.id)
      // })
  },
  methods: {
    initMenu () {
      let routers = this.$router.options.routes
      function loop (arr) {
        return arr.filter(e => !e.hidden).map(e => {
          let obj = {
            id: e.meta.id,
            text: e.meta.title,
            active: e.meta.active,
            link: e.name,
            tab: e.meta.tab,
            parent: e.meta.parent,
            children: []
          }
          if (e.meta.icon) {
            obj.icon = e.meta.icon
          }
          if (e.children && e.children.length) {
            obj.children = loop(e.children)
          }
          return obj
        })
      }
      let menuList = loop(routers)
      menuList.forEach(m => {
        let thirdRoute = m.children.filter(e => /\d-\d-\d/.test(e.id)) //找到三级id路由
        if (thirdRoute.length) {
          let o = {}
          thirdRoute.forEach(e => {
            let id = e.id && e.id.slice(0, 3)
            if (o[id]) {
              o[id].push(e)
            } else {
              o[id] = [e]
            }
          })
          // 对多组折叠路由进行替换
          Object.values(o).forEach(s => {
            let obj = {
              id: s[0].id.slice(0, 3),
              text: s[0].parent,
              active: s[0].active,
              type: 'group',
              isOpen: true,
              children: s
            }
            let idx = m.children.findIndex(e => e.id === s[0].id) // 找到需折叠路由第一次出现的idx
            m.children = m.children.filter(e => e.id.indexOf(obj.id) !== 0) // 过滤掉对应id的折叠路由
            m.children.splice(idx, 0, obj)
          })
        }
      })
      this.openName = [menuList[0].id]
      console.log(menuList)
      this.activeName = menuList[0].children.length && menuList[0].children[0].children[0].id
      this.menuList = menuList
    },
    openMenu (id) {
      if (!id) return
      let idList = id.split('-')
      this.activeName = id
      this.openName = [idList[0]]
      this.$nextTick(() => {
        this.$refs.side_menu.updateOpened()
        this.$refs.side_menu.updateActiveName()
      })
      // switch(idList.length) {
      //   case 2:
      //     this.onMenuChildrenSelect(idList[0] + '-' + idList[1], false)
      //     break
      //   case 3:
      //     this.onMenuItemSelect(id, false)
      //     break
      // }
    },
    clearCache () {
      // this.$cache = {...this.$back};
      // console.log(this.$cache['2-1-?'].serviceForm);
    },
    // 一级菜单选择
    onMenuSelect (menuId) {
      this.menuList.forEach(menu => {
        if (menu.id === menuId) {
          menu.active = true
          if (menu.children && menu.children.length) {
            // 默认选择第一个
            menu.children.forEach((children, j) => {
              if (j === 0 && children.type !== 'group') {
                children.active = true
                if (children.link) {
                  this.$router.push({
                    name: children.link
                  })
                }
              } else if (j === 0 && children.type === 'group') {
                let target = children.children[0]
                if (target && target.link) {
                  target.active = true
                  this.$router.push({
                    name: target.link,
                    query: {
                      tab: target.tab
                    }
                  })
                }
              }
            })
          }
        } else {
          menu.active = false
          // if (menu.children && menu.children.length) {
          //     menu.children.forEach(child => {
          //         child.active = false
          //     });
          // }
        }
      })
    },
    // 二级菜单选择
    onMenuChildrenSelect (childrenId, jump = true) {
      let idList = childrenId.split('-')
      let menu = this.menuList.find(obj => obj.id === idList[0])
      this.menuList.forEach(obj => obj.active = obj.id === menu.id)
      menu.children.forEach(children => {
        // 取消所有三级的 active
        if (children.type === 'group') {
          children.children.forEach(item => {
            item.active = false
          })
        } else {
          if (children.id === childrenId) {
            children.active = true
            if (jump && children.link) {
              this.$router.push({
                name: children.link
              })
            }
          } else {
            children.active = false
          }
        }
      })
      this.clearCache()
    },
    // 三级菜单选择
    onMenuItemSelect (itemId, jump = true) {
      let idList = itemId.split('-')
      let parentId = idList[0] + '-' + idList[1] // 最后一位 id 为 ？ 时使用
      let tab = this.$route.query.tab || 'tab1' // 最后一位 id 为 ？ 时使用
      let menu = this.menuList.find(menu => menu.id === idList[0])
      this.menuList.forEach(obj => obj.active = obj.id === menu.id)
      menu.children.forEach(children => {
        if (children.type !== 'group') {
          children.active = false
        } else {
          (children.children || []).forEach(item => this.checkMenuItem({ itemId, jump, idList, parentId, tab, item, children }))
        }
      })
    },
    // 三级菜单处理方式
    checkMenuItem ({ itemId, jump, idList, parentId, tab, item, children }) {
      if (jump) { // jump 模式，会跳页面
        if (item.id === itemId) {
          item.active = true
          // 判断是否有 link 和 是否有 tab
          if (item.link && item.tab) {
            //  直接跳页面
            this.$router.push({
              name: item.link,
              query: {
                tab: item.tab
              }
            })
          } else if (item.link) {
            this.$router.push({
              name: item.link
            })
          }
        } else {
          item.active = false
        }
      } else { // 非 jump 模式，只改变样式
        // id 最后一位是否为 ？ ，是则只判断前两位以及 tab (原先)
        // 路由配置修改，如果有三级路由并且存在tab
        if (idList[2] && item.tab) {
          // 取得当前循环 item 的上一级 id -> itemParentId
          let itemParentIdList = item.id.split('-')
          let itemParentId = itemParentIdList[0] + '-' + itemParentIdList[1]

          // 判断 parentId 相同 且和 route 的 tab 相同
          if (itemParentId === parentId && tab === item.tab) {
            // 打开三级菜单
            children.isOpen = true
            item.active = true
          } else {
            item.active = false
          }
        } else {
          item.active = item.id === itemId
          // 打开三级菜单
          // item.active && (children.isOpen = true);
        }
      }
    }
  }
}
</script>
